package com.itheima.controller;

import com.github.pagehelper.PageInfo;
import com.itheima.controller.results.Code;
import com.itheima.controller.results.Result;
import com.itheima.domain.Student;
import com.itheima.service.StudentService;
import com.itheima.system.Exception.BusinessException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/student")
public class StudentController {
    @Autowired
    private StudentService studentService;

        @GetMapping("/{page}/{size}")
    public Result getAll(@PathVariable Integer page,@PathVariable Integer size){
            PageInfo<Student> all = studentService.getAll(page, size);
            return new Result(null!=all? Code.GET_OK:Code.GET_ERROR,all);
        }

        @PostMapping
    public Result save(Student stu){
            boolean flag = studentService.save(stu);
            return new  Result(flag?Code.SAVE_OK:Code.SAVE_ERROR);
        }

        @DeleteMapping("/{uuid}")
    public Result delete(@PathVariable Integer uuid){
            boolean flag = studentService.delete(uuid);
            return new Result(flag?Code.DELETE_OK:Code.DELETE_ERROR);
        }

        @PutMapping
    public Result update(Student stu){
            boolean flag = studentService.update(stu);
            return new Result(flag?Code.UPDATE_OK:Code.UPDATE_ERROR);
        }

        @GetMapping("/{uuid}")
    public Result get(@PathVariable Integer uuid){
            Student stuOne = studentService.get(uuid);

            //假如uuid为10是没有的，所以要抛出异常信息
            if (uuid==10)throw new BusinessException("id不存在，请重试",Code.GET_ERROR);


            return new Result(null!=stuOne?Code.GET_OK:Code.GET_ERROR,stuOne);
        }

        @PostMapping("/login")
    public Result login(String name,Integer age){
            Student login = studentService.login(name, age);
            return new Result(null!=login?Code.GET_OK:Code.GET_ERROR,login);
        }


}
